package edu.pku.sei.transformation.qvt.engine.modelmorf;

import java.io.File;

import edu.pku.sei.transformation.codegen.CodegenRegister;
import edu.pku.sei.transformation.editor.model.AtomicTransformation;
import edu.pku.sei.transformation.editor.model.MetaModel;
import edu.pku.sei.transformation.editor.model.ModelType;
import edu.pku.sei.transformation.editor.model.TypedModel;
import edu.pku.sei.transformation.editor.model.execution.Pin;
import edu.pku.sei.transformation.editor.model.execution.TransformationExecution;
import edu.pku.sei.transformation.engine.EngineExtraData;
import edu.pku.sei.transformation.engine.IEngineAdapter;
import edu.pku.sei.transformation.engine.IEngine;
import edu.pku.sei.transformation.execution.ExecutionEnvironment;
import edu.pku.sei.transformation.qvt.action.StandardQVTCodegenAdapter;

public class ModelMorfAdapter implements IEngineAdapter {

	@Override
	public IEngine getRunner(TransformationExecution execution,
			ExecutionEnvironment env) throws Exception {
		ModelMorfRunner runner = new ModelMorfRunner();
		if (!(execution.getTransformation() instanceof AtomicTransformation)) {
			throw new Exception("not support composite transformation");
		}

		TypedModel target = execution.getDirection();
		runner.targetDomain = target.getName();
		if (target == null) {
			throw new Exception("not define target");
		}
		for (TypedModel typedModel : execution.getTransformation()
				.getTypedModel()) {
			ModelType modelType = (ModelType) typedModel.getType();
			MetaModel metaModel = (MetaModel) modelType.getType();
			File metaModelFile = new File(metaModel.getFilePath().trim())
					.getAbsoluteFile();
			runner.metaModel.put(modelType.getName(), metaModelFile);

		}

		for (Pin pin : execution.getActualParameters()) {
			String path = env.getPath(pin);
			if (path != null) {
				File modelFile = new File(path.trim()).getAbsoluteFile();
				//System.out.println(path+" "+modelFile.getAbsolutePath());
				runner.model.put(pin.getFormalParameter().getName(), modelFile);
			}
		}
		
		CodegenRegister.INSTANCE.generateCodeIfNotExist(StandardQVTCodegenAdapter.LANGUAGE, execution);
		runner.qvtSpecificationFile = new File(execution.getCode(StandardQVTCodegenAdapter.LANGUAGE).getAbsolutePath());
		System.err.println(runner.qvtSpecificationFile.getAbsolutePath());
		runner.executionMode = execution.getModeString();
		runner.transformationName = execution.getTransformation().getName();

		return runner;
	}

	@Override
	public EngineExtraData getExtraData(EngineExtraData oringin) {
		return new ModelMorfExtraData(oringin);
	}

	@Override
	public String getID() {
		return "ModelMorf";
	}
}
